package com.tedu.servlet;

import com.tedu.dao.NewsTopicDao;
import com.tedu.pojo.News;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 处理与新闻相关的请求
 */
public class NewsServlet extends HttpServlet {

    NewsTopicDao dao ;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        methon=getnewslist&tid=${topic.tid}
        String methon = req.getParameter("methon");
        String tid = req.getParameter("tid");
        dao = new NewsTopicDao();//实例化dao对象

        //调用dao
        if(methon.equals("getnewslist"))
        {
            // 显示新闻列表
           List<News>  DATA =  dao.getNewsByTID(tid);
           //发送数据页面
            System.out.println(DATA);
            req.setAttribute("news",DATA);
            //转发页面
            req.getRequestDispatcher("news.jsp").forward(req,resp);

        }else if(methon.equals("readnews")){
            // 新闻阅读
            //获取nid
            String nid = req.getParameter("nid");
            List<News>  DATA =  dao.getNewsById(nid);
            News news;
            if (DATA.size()>0){
                news = DATA.get(0);
            }else {
                news = new News();
            }
            //发送数据  页面
            //向域中添加数据
            req.setAttribute("news",news);
            System.out.println(news);
            //转发readNews.jsp
            req.getRequestDispatcher("readNews.jsp").forward(req,resp);


        }

        // 发送页面

        System.out.println(methon+"正在处理用户的请求"+tid);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
